package cn.itcast.demo.lock;

import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
public class SimpleRedisLock implements RedisLock {

    private StringRedisTemplate redisTemplate;
    private String key;

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String key) {
        this.redisTemplate = redisTemplate;
        this.key = key;
    }

    private static final String VALUE_PREFIX = UUID.randomUUID().toString() + ":";

    @Override
    public boolean tryLock(long releaseTime) {
        // 设置value
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        // 获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        return BooleanUtils.isTrue(boo);
    }

    @Override
    public void unlock() {
        String value = VALUE_PREFIX + Thread.currentThread().getId();

        redisTemplate.execute(RedisScript.of("if(redis.call('get', KEYS[1]) == ARGV[1]) then\n" +
                "\tredis.call('del', KEYS[1])\n" +
                "end"), Collections.singletonList(key), value);

        /*// 获取锁中的值
        String cacheValue = redisTemplate.opsForValue().get(key);
        // 判断是否是自己的标识
        if(value.equalsIgnoreCase(cacheValue)){
            redisTemplate.delete(key);
        }*/
    }
}
